import {
  Dimensions,
  Image,
  NativeScrollEvent,
  NativeSyntheticEvent,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useCallback, useContext, useEffect, useState } from "react";
import Head from "../../components/Head";
import { SafeAreaView } from "react-native-safe-area-context";
import { Button } from "react-native-paper";
import { Https } from "../../api";
import { GlobalContext } from "../../hooks/reducer";
import { useNavigation, useRoute } from "@react-navigation/native";
import { ProductListItem, RootStackParamList } from "../../types";

import CartPopup from "../../components/CartPopup";

type ProductList = {
  totalCounts: number;
  totalPage: number;
  code: number;
  currentpage: number;
  data: Array<ProductListItem>;
};

const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height;

const ProductList = () => {
  const [productList, setProductList] = useState<Array<ProductListItem>>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [totalPage, setTotalPage] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageLoading, setPageLoading] = useState(false);
  const [goodsCode, setGoodsCode] = useState<string>("");
  const [gsColorCode, setGsColorCode] = useState<string>("");
  const [visible, setVisible] = useState(false);
  const [pageLoadingTitle, setPageLoadingTitle] = useState("加载中...");
  const [searchQuery, setSearchQuery] = React.useState("");
  const router = useRoute();
  const changeState: any = useContext(GlobalContext);
  const navigation = useNavigation();
  useEffect(() => {
    getFindGoodsList();
  }, []);

  const hideModal = () => {
    setVisible(false);
    // setScrollEnabled(true);
  };
  const onChangeSearch = (query: string) => setSearchQuery(query);
  //下拉刷新
  const wait = () => {
    return new Promise((resolve) => {
      getFindGoodsList().then(resolve);
    });
  };
  //下拉刷新
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    // setProductList([]);
    wait().then(() => setRefreshing(false));
  }, []);
  //上拉加载
  const onMomentumScrollEnd = (
    event: NativeSyntheticEvent<NativeScrollEvent>
  ) => {
    const offSetY = event.nativeEvent.contentOffset.y; // 获取滑动的距离
    const contentSizeHeight = event.nativeEvent.contentSize.height; // scrollView  contentSize 高度
    const residueScrollHeight = event.nativeEvent.layoutMeasurement.height; // scrollView高度

    if (offSetY + residueScrollHeight >= contentSizeHeight - 1) {
      setCurrentPage(() => currentPage + 1);
      setPageLoading(true);
      if (currentPage < totalPage) {
        getFindGoodsList();
        return;
      }
      setPageLoadingTitle("已加载完毕");
    }
  };

  const getFindGoodsList = async () => {
    changeState.dispatch({ type: "SetToLoad", payload: true });
    const { classifyId } = router.params as RootStackParamList["ProductList"];
    let params = {
      classifyIds: classifyId,
      currentpage: currentPage,
      sortType: 4,
      sortDirection: "",
      desc: "",
      goodsSelect: "",
      goodsLowPrice: "",
      goodsHighPrice: "",
      userBrand: "",
      size: "",
      pageSize: "",
    };

    const { code, data, totalPage }: ProductList = await Https.getFindGoodsList(
      params
    );

    if (!code) {
      setTotalPage(totalPage);
      changeState.dispatch({ type: "SetToLoad", payload: false });
      setPageLoading(false);
      if (currentPage !== 1) {
        setProductList(() => [...productList, ...data]);
        return;
      }
      setProductList(data);
    }
  };

  const handleVisible = (goodsCode: string, gsColorCode: string) => {
    setGoodsCode(goodsCode);
    setGsColorCode(gsColorCode);
    setVisible(true);
  };

  const handleViewDetails = (goodsId: string, goodsColor: string) => {
    navigation.navigate("ProductDetails", { goodsId, goodsColor });
  };

  return (
    <SafeAreaView style={{ backgroundColor: "#fff" }}>
      <Head />
      {/* <Searchbar
        placeholder="Search"
        onChangeText={onChangeSearch}
        value={searchQuery}
      /> */}

      <ScrollView
        style={{ minHeight: 800 }}
        showsVerticalScrollIndicator={false}
        keyboardDismissMode={"on-drag"}
        onScrollEndDrag={onMomentumScrollEnd}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            title="下拉刷新"
          />
        }
      >
        <View style={styles.ProductListMain}>
          {productList &&
            productList.map(
              ({
                id,
                gscMaincolPath,
                discount,
                goodsName,
                discountPrice,
                originalPrice,
                goodsCode,

                gsColorCode,
              }) => (
                <View style={styles.ProductContent} key={id}>
                  <TouchableOpacity
                    activeOpacity={0.8}
                    onPress={() => handleViewDetails(goodsCode, gsColorCode)}
                  >
                    <Image
                      style={styles.ProductContentImg}
                      resizeMethod={"scale"}
                      source={{
                        uri: `https://cdn.bestseller.com.cn${gscMaincolPath}`,
                      }}
                    />
                    {discount !== 1 && (
                      <Image
                        style={styles.ProductContentIcon}
                        resizeMethod={"scale"}
                        source={{
                          uri: `https://cdn.bestseller.com.cn/coverPic/discountImg.png`,
                        }}
                      />
                    )}
                    <Text style={styles.ProductContentName} numberOfLines={1}>
                      {goodsName}
                    </Text>
                    <View style={styles.ProductContentPrice}>
                      <Text style={{ fontSize: 16 }}>￥ {discountPrice}</Text>
                      {discount !== 1 && (
                        <Text style={styles.discount}>￥{originalPrice}</Text>
                      )}
                      {discount !== 1 && (
                        <Text style={styles.ProductContentDiscount}>
                          {(discount * 10).toFixed(1)}折
                        </Text>
                      )}
                    </View>
                  </TouchableOpacity>

                  <View style={styles.ProductContentButton}>
                    <Button
                      mode="contained"
                      textColor="#fff"
                      buttonColor="#000"
                      style={{ borderRadius: 2, width: 150 }}
                      compact={true}
                      onPress={() => handleVisible(goodsCode, gsColorCode)}
                    >
                      加入购物车
                    </Button>
                  </View>
                </View>
              )
            )}
          {pageLoading && (
            <Text style={styles.pageLoadingTitle}>{pageLoadingTitle}</Text>
          )}
        </View>
      </ScrollView>

      <CartPopup
        type="addCart"
        visible={visible}
        hideModal={hideModal}
        goodsCode={goodsCode}
        gsColorCode={gsColorCode}
      ></CartPopup>
    </SafeAreaView>
  );
};

export default ProductList;

const styles = StyleSheet.create({
  ProductListMain: {
    width,
    marginBottom: 150,
    flexDirection: "row",
    flexWrap: "wrap",
    backgroundColor: "#fff",
  },
  ProductContent: {
    width: width * 0.45,
    marginLeft: width * 0.03,
    marginTop: 20,
  },
  ProductContentImg: {
    width: "100%",
    height: 300,
    borderRadius: 5,
  },
  ProductContentIcon: {
    position: "absolute",
    right: 0,
    top: 0,
    height: 60,
    width: 60,
  },
  ProductContentName: {
    paddingVertical: 10,
  },
  ProductContentPrice: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-evenly",
  },
  ProductContentDiscount: {
    padding: 3,
    borderRadius: 3,
    fontSize: 12,
    borderStyle: "solid",
    borderWidth: 1,
    borderColor: "#ff3333",
    color: "#ff3333",
    backgroundColor: "#fffbfe",
  },
  ProductContentButton: {
    width: "100%",
    marginTop: 20,
    justifyContent: "center",
    alignItems: "center",
  },
  pageLoadingTitle: {
    width: "100%",
    height: 50,
    textAlign: "center",
    lineHeight: 50,
    fontSize: 14,
    color: "#ccc",
  },
  discount: {
    textDecorationLine: "line-through",
    color: "#929090",
    fontSize: 16,
  },
  DrawerMenuImg: {
    height: 150,
    width: 120,
  },
  DrawerMenuTitle: {
    paddingTop: 10,
    paddingHorizontal: 30,
    fontSize: 16,
    fontWeight: "600",
  },
  DrawerMenuPriceMain: {
    width: 130,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-evenly",
    paddingVertical: 10,
  },
  DrawerMenuPrice: {
    // paddingRight:20,
    fontSize: 16,
    fontWeight: "600",
    color: "#ff3333",
  },
});
